package de.chludwig.ehumanities.provenance.background;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.chludwig.ehumanities.provenance.utils.ZipUtil;

/**
 * 
 */
public class ZipArchiveTask implements Runnable {

  private static final String TMP_ZIP_FILE_EXTENSION = ".tmp";

  private static final int COMPRESSION_LEVEL = 9;
  
  private static final Logger LOG = LoggerFactory.getLogger(ZipArchiveTask.class); 

  private static final String MSG_START_ARCHIVING = "creation of zip archive {} started";
  
  private static final String MSG_FINISHED_ARCHIVING = "creation of zip archive {} complete";
  
  private static final String MSG_ZIP_FAILED = "failed to create zip archive {}";
  
  private File archiveFolder;
  private File zipFile;

  public ZipArchiveTask(File archiveFolder, File zipFile) {
    this.archiveFolder = archiveFolder;
    this.zipFile = zipFile;
  }

  /**
   * @return the archiveFolder
   */
  public File getArchiveFolder() {
    return archiveFolder;
  }

  /**
   * @return the zipFile
   */
  public File getZipFile() {
    return zipFile;
  }

  public File getTmpZipFile() {
    File base = getZipFile();
    File parent = base.getParentFile();
    String name = base.getName() + TMP_ZIP_FILE_EXTENSION;
    return new File(parent, name);
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    File tmpZipFile = getTmpZipFile();
    File targetFile = getZipFile();

    String archiveFileName = targetFile.getName();
    LOG.info(MSG_START_ARCHIVING, archiveFileName);
    
    ZipUtil compressor = new ZipUtil();
    compressor.setCompressionLevel(COMPRESSION_LEVEL);
    try {
      compressor.archiveRecursively(getArchiveFolder(), tmpZipFile);
      tmpZipFile.renameTo(targetFile);
      LOG.info(MSG_FINISHED_ARCHIVING, archiveFileName);
    }
    catch (IOException ex) {
      LOG.error(MSG_ZIP_FAILED, archiveFileName, ex);
    }
  }

}